package com.wuchengdong.web.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuchengdong.web.extend.auth.AuthTemplate;
import com.wuchengdong.web.extend.exception.AuthException;
import com.wuchengdong.web.extend.utils.UserHolder;
import com.wuchengdong.web.pojo.User;
import com.wuchengdong.web.service.UserService;
import com.wuchengdong.web.extend.utils.R;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import static com.wuchengdong.web.extend.utils.CookieUtil.getByName;

/**
 * 登录校验 <br/>
 * 使用cookie后 感觉校验的责任全部给了cookie和拦截器，Login只是为了获取token，自动登录只是为了让前端拿到user信息
 */
@RestController
@RequestMapping("/auth")
public class  AuthController {

    @Autowired
    UserService userService;

    //策略模式 + 模板方法 + 简单工厂
    @Autowired
    AuthTemplate authTemplate;

    @PostMapping("/login")

    public R<String> login(@RequestBody User _user) {
        //检查用户名密码
        User user = userService.checkPassword(_user);
        if (ObjectUtil.isEmpty(user)) return R.error("用户名或密码错误");

        //生成唯一token 储存
        String token = authTemplate.saveNewTokenWithUser(user);

        return R.success(token);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {

        authTemplate.cleanTokenWithUser(
                getByName(request.getCookies(), "auth").getValue(),
                UserHolder.getUserPk()
        );

        return R.success("退出");
    }

    @PostMapping("/register")
    public R<String> register(@RequestBody User user) {
        //根据name搜索是否有同名用户
        User user1 = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getName, user.getName()));
        if (ObjectUtil.isNotEmpty(user1)) return R.error("用户名重复");
        else {
            userService.save(user);
            //生成唯一token 储存
            String token = authTemplate.saveNewTokenWithUser(user);
            return R.success(token);
        }
    }

    //自动登录校验
    @PostMapping("/autoLogin")
    public R<User> autoLogin(HttpServletRequest request) throws AuthException {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if(ObjectUtil.isEmpty(request.getCookies())){
            return R.error("请先登录");
        }
        String token = getByName(request.getCookies(), "auth").getValue();
        int id = authTemplate.getUserByToken(token);
        if (id == -1) throw new AuthException("找不到对应用户,token:"+token);

        User user = userService.getById(id);

        return R.success(user);
    }
}
